package ldh.serialize.type;

import ldh.serialize.BinarySerialized;
import ldh.serialize.io.ByteBuf;
import ldh.serialize.util.SerializedUtil;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateTimeSerialized implements BinarySerialized<LocalDateTime> {

	@Override
	public void write(ByteBuf out, LocalDateTime localDateTime) {
		Long time = null;
		if (localDateTime != null) {
			time  = Timestamp.valueOf(localDateTime).getTime();
		}
		SerializedUtil.writeLong(out, time);
	}

	@Override
	public LocalDateTime read(ByteBuf in) {
		Long time = SerializedUtil.readLong(in);
		if (time == null) {
			return null;
		}
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(time), ZoneId.systemDefault());
		return localDateTime;
	}

	@Override
	public Class<LocalDateTime> getClassType() {
		return LocalDateTime.class;
	}

}
